package com.bby.disk.manager.mfile;

import java.io.Serializable;

public class MPath implements Serializable {
    protected String parent,name,userId;
    public static String separator = "/";
    public MPath(String parent, String name) {
        this.parent=modifyPath(parent);
        userId=this.parent.split(separator)[0];
        this.name=name;
    }
    public MPath(String path) {
        path=modifyPath(path);
        int pos = path.lastIndexOf(separator);
        if (pos==-1){
            this.parent="";
            this.name=path;
            this.userId=path;
        }else{
            this.parent = path.substring(0,pos);
            this.name = path.substring(pos+1);
            this.userId=path.substring(0,path.indexOf(separator));
        }
    }

    public MPath(MPath parent, String child) {
        this(parent.getPath(),child);
    }

    private String modifyPath(String path){
        path=path.replaceAll("/+|\\\\+",separator);
        int st = path.startsWith(separator)? 1:0;
        int en = path.endsWith(separator)? path.length()-1:path.length();
        if (st>en)return "";
        return path.substring(st,en);
    }

    public String getUserId() {
        return userId;
    }

    public String getPath(){
        return modifyPath(parent+separator+name);
    }

    public String getParent() {
        return parent;
    }

    public String getName() {
        return name;
    }

    public boolean check(){
        String path =getPath();
        System.out.println("path = " + path);
        if (userId==null||userId.length()==0) return false;
        if (path.matches("[0-9]*")) return true;
        if (!path.matches("[0-9]*/.*") ||path.matches(".*(\\./)+.*")
                ||path.matches("^.*[:<>|\\*\\?]+.*$")){
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "MFile{" +
                "parent='" + parent + '\'' +
                ", name='" + name + '\'' +
                ", userId='" + userId + '\'' +
                '}';
    }
}
